<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="auto">

      <el-form-item label="省份或直辖市" prop="province">
        <el-select v-model="queryParams.province" placeholder="请选择省份或直辖市" @change="handleProvinceChange" clearable>
          <el-option v-for="item in regionData" :key="item.label" :label="item.label" :value="item.label" />
        </el-select>
      </el-form-item>

      <el-form-item label="城市名称" prop="city">
        <el-select v-model="queryParams.city" placeholder="请选择城市" @change="handleCityChange" clearable>
          <el-option v-for="item in cityOptions" :key="item.label" :label="item.label" :value="item.label" />
        </el-select>
      </el-form-item>
      <el-form-item label="区域名称" prop="region">
        <el-select v-model="queryParams.region" placeholder="请选择区域" clearable>
          <el-option v-for="item in regionOptions" :key="item.label" :label="item.label" :value="item.label" />
        </el-select>
      </el-form-item>

      <el-form-item label="自定义编码" prop="customCode">
        <el-input v-model="queryParams.customCode" placeholder="请输入自定义编码" />
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['service:district:add']">新建</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-permission="['service:district:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['service:district:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['service:district:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="districtList" @selection-change="handleSelectionChange"
      @row-dblclick="handleRowDbClick">
      <!-- 将原来的这一列：
  <el-table-column label="主键，自增ID" align="center" prop="id" />
-->
      <el-table-column type="index" label="" align="center"  width="50" />
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="地区编码" align="center" prop="location" />
      <el-table-column label="自定义编码" align="center" prop="customCode" />
      <el-table-column label="省份或直辖市名称" align="center" prop="province" />
      <el-table-column label="城市名称" align="center" prop="city" />
      <el-table-column label="区域名称" align="center" prop="region" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['service:district:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['service:district:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改区域管理对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body draggable :close-on-click-modal="false"
      :close-on-press-escape="false" :show-close="false">

      <el-form ref="districtRef" :model="form" :rules="rules" label-width="auto">

        <!-- :props="{ checkStrictly: true }" -->
        <el-form-item label="所在地区" prop="locationArr">
          <el-cascader v-model="form.locationArr" style="width: 100%" placeholder="请选择省市区" :options="regionData"
            @change="handleFormChange" />
        </el-form-item>

        <el-form-item label="省份或直辖市名称" prop="province">
          <el-input v-model="form.province" placeholder="省份或直辖市名称" readonly />
        </el-form-item>
        <el-form-item label="城市名称" prop="city">
          <el-input v-model="form.city" placeholder="城市名称" readonly />
        </el-form-item>
        <el-form-item label="区域名称" prop="region">
          <el-input v-model="form.region" placeholder="区域名称" readonly />
        </el-form-item>
        <el-form-item label="自定义编码" prop="customCode">
          <el-input v-model="form.customCode" placeholder="请输入自定义编码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="District">
import { listDistrict, getDistrict, delDistrict, addDistrict, updateDistrict } from "@/api/service/district"
//import { listDistrict, deleteDistrict, addDistrict, updateDistrict } from '@/api/base/district'
//import { regionData, CodeToText, TextToCode } from 'element-china-area-data'
//import { regionData, codeToText, textToCode } from 'element-china-area-data'
//import { provinceAndCityData‌, regionData, provinceAndCityDataPlus‌, regionDataPlus‌, codeToText } from 'element-china-area-data'
//import { regionDataPlus‌, regionData, codeToText } from 'element-china-area-data'
import { 
  provinceAndCityData,  // 省市二级联动数据(不带"全部"选项)
  regionData,          // 省市区三级联动数据(不带"全部"选项)
  pcTextArr,           // 省市联动数据(纯汉字)
  pcaTextArr,          // 省市区联动数据(纯汉字)
  codeToText          // 区域码转汉字对象
} from 'element-china-area-data'

// 城市选项
const cityOptions = ref([])
// 区域选项
const regionOptions = ref([])

const { proxy } = getCurrentInstance()

const districtList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const props = defineProps({
  isModal: {
    type: Boolean,
    default: true
  },
  center: {
    type: Boolean,
    default: true
  }
})

const currentSelected = ref({})
const emit = defineEmits(['select'])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    region: null,
    province: null,
    city: null,
    locationArr: null,
    location: null,
    customCode: null
    
  },
  rules: {
    region: [
      { required: true, message: "区域名称不能为空", trigger: "blur" }
    ],
    province: [
      { required: true, message: "省份名称不能为空", trigger: "blur" }
    ],
    city: [
      { required: true, message: "城市名称不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询区域管理列表 */
function getList() {
  loading.value = true

  listDistrict(queryParams.value).then(response => {
    districtList.value = response.rows
    total.value = response.total;
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    province: null,
    city: null,
    region: null,
    districtComb: null,
    locationArr: null,
    location: null,
    customCode: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    deleted: null
  }
  proxy.resetForm("queryRef") //搜索条件也需重置

  proxy.resetForm("districtRef")
}

function handleParamsChange() {
  //queryParams = convertLocationToText(queryParams.value)
  const queryData = { ...queryParams.value }

  //alert('queryData.location=' + queryData.location)
  // 如果使用了级联选择器，则转换编码为文字
  if (queryData.locationArr && queryData.locationArr.length > 0) {
    queryParams.value.province = codeToText[queryData.locationArr[0]] || ''
    if (queryData.locationArr.length > 1) {
      queryParams.value.city = codeToText[queryData.locationArr[1]] || ''
    }
    if (queryData.locationArr.length > 2) {
      queryParams.value.region = codeToText[queryData.locationArr[2]] || ''
    }
  }

  /*queryData.pageNum = 1
  loading.value = true
  listDistrict(queryData).then(response => {
    districtList.value = response.rows
    total.value = response.total
    loading.value = false
  })*/
}


function handleFormChange() {
  //queryParams = convertLocationToText(queryParams.value)
  const queryData = { ...form.value }
  
  // 如果使用了级联选择器，则转换编码为文字
  if (queryData.locationArr && queryData.locationArr.length > 0) {
    form.value.province = codeToText[queryData.locationArr[0]] || ''
    if (queryData.locationArr.length > 1) {
      form.value.city = codeToText[queryData.locationArr[1]] || ''
    }
    if (queryData.locationArr.length > 2) {
      form.value.region = codeToText[queryData.locationArr[2]] || ''
    }
  }

  //form.value.district_comb = form.value.province + "/" + form.value.city + "/" + form.value.region
  form.value.districtComb = form.value.province + form.value.city + form.value.region

    if (queryData.locationArr && Array.isArray(queryData.locationArr)) {
    form.value.location = queryData.locationArr[2]
    //alert('queryData.location=' + form.value.location)
  }

  /*queryData.pageNum = 1
  loading.value = true
  listDistrict(queryData).then(response => {
    districtList.value = response.rows
    total.value = response.total
    loading.value = false
  })*/
}

function handleProvinceChange(provinceName) {
  queryParams.value.city = ''
  cityOptions.value = []
  queryParams.value.region = ''
  regionOptions.value = []

  // 根据选中的省份名称查找对应的省份对象
  const province = regionData.find(p => p.label === provinceName)
  
  // 如果找到了省份且有子级（城市）数据
  if (province && province.children) {
    // 更新城市选项为该省份下的城市列表
    cityOptions.value = province.children
  } else {
    // 如果没有找到或没有子级数据，则清空城市选项
    cityOptions.value = []
  }
}

function handleCityChange(cityName) {
   queryParams.value.region = ''
   regionOptions.value = []

  // 首先需要找到对应的省份，因为regionData是按省份->城市->区域的层级结构组织的
  const provinceName = queryParams.value.province;
  if (!provinceName || !cityName) {
    regionOptions.value = [];
    return;
  }

  // 在regionData中查找对应的省份
  const province = regionData.find(p => p.label === provinceName);
  if (!province || !province.children) {
    regionOptions.value = [];
    return;
  }

  // 在省份的子级中查找对应的城市
  const city = province.children.find(c => c.label === cityName);
  if (!city || !city.children) {
    regionOptions.value = [];
    return;
  }

  // 更新区域选项为该城市下的所有区域
  regionOptions.value = city.children;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length

  if (selection.length > 0) 
     currentSelected.value = selection[0]
}

/* // 多选框选中数据（实现单选行为）
function handleSelectionChange(selection) {
  // 如果选择了多个，则只保留最后一个
  if (selection.length > 1) {
    // 清除所有选择
    proxy.$refs.tableRef?.clearSelection()
    // 只选择最后一个
    proxy.$refs.tableRef?.toggleRowSelection(selection[selection.length - 1], true)
    selection = [selection[selection.length - 1]]
  }
  
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
  
  // 记录当前选择项
  if (selection.length === 1) {
    currentSelected.value = selection[0]
  }
} */


/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加区域管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getDistrict(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改区域管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["districtRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateDistrict(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addDistrict(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除区域管理编号为"' + _ids + '"的数据项？').then(function() {
    return delDistrict(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('service/district/export', {
    ...queryParams.value
  }, `district_${new Date().getTime()}.xlsx`)
}

// 数字转文字
function convertLocationToText(dataForm) {
   dataForm.province = ''
   dataForm.city = ''
   dataForm.region = ''
  // 如果使用了级联选择器，则转换编码为文字
  // 转换省市县区
  const ad = dataForm.location
  if (ad && ad.length > 0) {
    dataForm.province = codeToText[ad[0]] || ''
    if (ad.length > 1) {
      dataForm.city = codeToText[ad[1]] || ''
    }
    if (ad.length > 2) {
      dataForm.region = codeToText[ad[2]] || ''
    }
  }

  return dataForm
}


// 双击行事件
function handleRowDbClick(row) {
  if (!props.isModal) {
    emit('select', row)
  }
}

// 确认选择
function handleSelectConfirm() {
  if (Object.keys(currentSelected.value).length > 0) {
    emit('select', currentSelected.value)
  }
}


getList()

// 向外暴露方法
defineExpose({
  handleSelectConfirm
})

</script>
